<script setup lang="ts">
import XtxSwiper from '@/components/XtxSwiper.vue'
import CustomNavbar from './components/CustomNavbar.vue'
import { getBannerAPI, getHomeCategoryAPI, gethomeHotAPI } from '@/services/Home'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CategoryPanel from './components/CategoryPanel.vue'
import type { XtxGuessInstance } from '@/types/component'
import HotPanel from './components/HotPanel.vue'
import PageSkeleton from './components/PageSkeleton.vue'

const bannerList = ref<BannerItem[]>([])

const getBannerData = async () => {
  const res = await getBannerAPI()
  console.log(res)
  bannerList.value = res.result
}

const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()

  categoryList.value = res.result
}

//热门数据区获取
const hotList = ref<HotItem[]>([])
const gethomeHotData = async () => {
  const res = await gethomeHotAPI()
  hotList.value = res.result
}

//获取猜你喜欢的组件
const guessRef = ref<XtxGuessInstance>()
//触底执行此函数
const onScrolltolower = () => {
  // console.log('haha')
  guessRef.value?.getMore()
}

const isTriggered = ref(false)

//自定义刷新下拉被处触发
const onRefresherrefresh = async () => {
  // console.log('下拉触发此函数')
  // 开启动画
  isTriggered.value = true
  //加载数据
  guessRef.value?.resetGuessData()
  await Promise.all([getBannerData(), getHomeCategoryData(), gethomeHotData()])
  //关闭动画
  isTriggered.value = false
}
//uni-app的生命周期函数
const isLoading = ref(false)
onLoad(() => {
  isLoading.value = true
  Promise.all([getBannerData(), getHomeCategoryData(), gethomeHotData()]), (isLoading.value = false)
})
</script>

<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar></CustomNavbar>

  <!-- scroll-view 是微信小程序原生框架和跨平台框架（如 UniApp）
   中用于实现可滚动视图区域的核心组件 refresher-enabled 开启下拉刷新功能 @refresherrefresh 下拉刷新触发函数 
   refresher-triggered 是否显示刷新动画 true 显示，fasle不显示
   scrolltolower 触底触发此函数 -->
  <scroll-view
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="onScrolltolower"
    :refresher-triggered="isTriggered"
    class="scroll-view"
    scroll-y
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 轮播图 -->
      <XtxSwiper :list="bannerList"></XtxSwiper>
      <!-- 首页分类 -->
      <CategoryPanel :list="categoryList"></CategoryPanel>
      <!-- 热门推荐 -->
      <HotPanel :list="hotList"></HotPanel>
      <XtxGuess ref="guessRef"></XtxGuess>
    </template>
  </scroll-view>
</template>

<style lang="scss">
//
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
